import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:ugrownews_flutter/main/ScreenNewsDetail.dart';
import 'package:ugrownews_flutter/main/main_item/MainBannerSwiper.dart';
import 'package:ugrownews_flutter/utils/RouterUtil.dart';
import 'package:ugrownews_flutter/utils/TextUtil.dart';
import 'package:ugrownews_flutter/utils/UGrowColors.dart';
import 'package:ugrownews_flutter/utils/netutil/NetUtil.dart';
import 'package:ugrownews_flutter/utils/netutil/NewsNetUtil.dart';

import 'package:flutter/cupertino.dart';

import 'package:flutter_easyrefresh/easy_refresh.dart';

/// FragmentMainNews
/// 新闻页
///

class FragmentMainNews extends StatefulWidget {
  @override
  _FragmentMainNewsState createState() {
    _FragmentMainNewsState _fragmentMainNewsState = _FragmentMainNewsState();
    _initData(_fragmentMainNewsState, 1, 20);
    return _fragmentMainNewsState;
  }
}

Future<dynamic> _initData(
    //初始化数据
    _FragmentMainNewsState _fragmentMainNewsState,
    int page,
    int pageSize) {
  Map<String, String> params = new Map();
  params["page"] = page.toString();
  params["pageSize"] = pageSize.toString();
  params["id"] = "24";
  return new NewsNetUtil().getNewsList(params, (result, isCache) {
    _fragmentMainNewsState.isLoading = false;
    if (result is NetError) {
      return;
    } else {
      Map jsonResult = json.decode(result);
      String state = jsonResult["state"];
      if (state.isNotEmpty && state == "success") {
        if (_fragmentMainNewsState.mounted) {
          _fragmentMainNewsState.setState(() {
            List<dynamic> data = jsonResult["data"];
            if (page == 1) {
              _fragmentMainNewsState.data = data;
            } else {
              _fragmentMainNewsState.data.addAll(data);
            }
          });
        }
      }
    }
  });
}

class _FragmentMainNewsState extends State<FragmentMainNews>
    with AutomaticKeepAliveClientMixin {
  List<dynamic> data = new List();
  int page = 1;
  bool isLoading = false;

  ScrollController controller = new ScrollController();
  GlobalKey<EasyRefreshState> _easyRefreshKey =
      new GlobalKey<EasyRefreshState>();

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return new Container(
      //Refresh，第三方上拉加载，下拉刷新库
      child: data.length > 0
          ? new EasyRefresh(
              key: _easyRefreshKey,
              onRefresh: _onRefresh,
              loadMore: _loadMore,
              child: new ListView.builder(
                controller: controller,
                padding: EdgeInsets.all(0),
                itemCount: data.length + 1,
                itemBuilder: _buildItem,
              ),
            )
          : new Center(
              child: new GestureDetector(
                child: new Text("正在加载"),
                onTap: () {
                  _initData(this, page, 10);
                },
              ),
            ),
    );
  }

  Future<dynamic> _onRefresh() {
    if (!isLoading) {
      isLoading = true;
      page = 1;
      return _initData(this, page, 10);
    }
  }

  Future<dynamic> _loadMore() async {
    if (!isLoading) {
      isLoading = true;
      page++;
      return _initData(this, page, 10);
    }
  }

  //构建条目
  Widget _buildItem(BuildContext context, int index) {
    //因为前边多了一个banner，所以将index-1
    index = index - 1;
    if (index == -1) {
      return new Container(
        width: ScreenUtil.screenWidthDp,
        height: ScreenUtil.instance.setWidth(608),
        child: new Stack(
          children: <Widget>[
            new Image.asset(
              "images/image_loading1.png",
              height: ScreenUtil.getInstance().setWidth(608),
              width: ScreenUtil.screenWidthDp,
              fit: BoxFit.fill,
            ),
            new Container(
                width: ScreenUtil.screenWidthDp,
                height: ScreenUtil.instance.setWidth(608),
                child: new MainBannerSwiper()),
          ],
        ),
      );
    } else {
      Widget item;
      switch (data[index]["customType"]) {
        case 0:
          item = _createSingleImageItem(data[index]);
          break;
        case 1:
          item = _createSingleImageTitleItem(data[index]);
          break;
        case 2:
          item = _createThreeImageItem(data[index]);
          break;
        default:
          item = _createSingleImageItem(data[index]);
          break;
      }
      //给item添加GestureDetector，点击跳转详情页
      return new GestureDetector(
        child: item,
        onTap: () {
          Map<String, dynamic> params = new Map();
          params["id"] = data[index]["id"];
          RouterUtil.getInstance().navigateTo(
            context,
            RouterUtil.ROUTER_NEWSDETAIL +
                "?id=" +
                data[index]["id"].toString(),
            transition: TransitionType.cupertino,
          );
        },
      );
    }
  }

  @override
  bool get wantKeepAlive => true;

  //单张图Item
  Widget _createSingleImageItem(data) {
    return new Container(
      height: ScreenUtil.getInstance().setWidth(222 + 28 + 29),
      width: ScreenUtil.screenWidthDp,
      padding: new EdgeInsets.only(
          left: ScreenUtil.getInstance().setWidth(36),
          right: ScreenUtil.getInstance().setWidth(36),
          top: ScreenUtil.getInstance().setWidth(28)),
      child: new Stack(
        children: <Widget>[
          new CachedNetworkImage(
            imageUrl: data["customImage"],
            placeholder: (context, url) {
              return new Image.asset(
                "images/image_loading1.png",
                height: ScreenUtil.getInstance().setWidth(222),
                width: ScreenUtil.getInstance().setWidth(294),
                fit: BoxFit.fill,
              );
            },
            errorWidget: (context, url, builder) {
              return new Icon(Icons.error);
            },
            height: ScreenUtil.getInstance().setWidth(222),
            width: ScreenUtil.getInstance().setWidth(294),
            fit: BoxFit.fill,
          ),
          new Positioned(
            width: ScreenUtil.screenWidthDp -
                ScreenUtil.getInstance().setWidth(360) -
                ScreenUtil.getInstance().setWidth(36),
            left: ScreenUtil.getInstance().setWidth(360 - 36),
            child: new Text(
              data["title"],
              maxLines: 2,
              softWrap: true,
              overflow: TextOverflow.ellipsis,
              style: new TextStyle(
                  color: UGrowColors.getColor("#333333"),
                  fontSize: ScreenUtil.getInstance().setWidth(48)),
            ),
          ),
          new Positioned(
            bottom: ScreenUtil.getInstance().setWidth(28),
            child: new Text(
              getPublishDate(data),
              maxLines: 1,
              style: new TextStyle(
                  color: UGrowColors.getColor("#999999"),
                  fontSize: ScreenUtil.getInstance().setWidth(38)),
            ),
            left: ScreenUtil.getInstance().setWidth(330),
          ),
          new Positioned(
            bottom: 0,
            height: ScreenUtil.getInstance().setWidth(2),
            child: new Container(
              height: ScreenUtil.getInstance().setWidth(2),
              width: ScreenUtil.screenWidthDp -
                  ScreenUtil.getInstance().setWidth(36 + 36),
              color: UGrowColors.getColor("#cccccc"),
            ),
          ),
        ],
      ),
    );
  }

  //单张大图Item
  Widget _createSingleImageTitleItem(data) {
    return new Container(
      width: ScreenUtil.screenWidthDp,
      child: new Column(
        children: <Widget>[
          new Container(
            alignment: Alignment.centerLeft,
            height: ScreenUtil.getInstance().setWidth(450),
            margin: new EdgeInsets.only(
              top: ScreenUtil.getInstance().setWidth(40),
              left: ScreenUtil.getInstance().setWidth(36),
              right: ScreenUtil.getInstance().setWidth(36),
            ),
            width: ScreenUtil.screenWidthDp -
                ScreenUtil.getInstance().setWidth(36 + 36),
            child: new CachedNetworkImage(
              imageUrl: data["customImage"],
              placeholder: (context, url) {
                return new Image.asset(
                  "images/image_loading1.png",
                  height: ScreenUtil.getInstance().setWidth(608),
                  width: ScreenUtil.screenWidthDp,
                  fit: BoxFit.fill,
                );
              },
              errorWidget: (context, url, builder) {
                return new Icon(Icons.error);
              },
              height: ScreenUtil.getInstance().setWidth(608),
              width: ScreenUtil.screenWidthDp,
              fit: BoxFit.fill,
            ),
          ),
          new Container(
            margin: new EdgeInsets.only(
              top: ScreenUtil.getInstance().setWidth(40),
              left: ScreenUtil.getInstance().setWidth(36),
              right: ScreenUtil.getInstance().setWidth(36),
            ),
            width: ScreenUtil.screenWidthDp -
                ScreenUtil.getInstance().setWidth(36 + 36),
            child: new Text(
              data["title"],
              maxLines: 1,
              softWrap: true,
              overflow: TextOverflow.ellipsis,
              textAlign: TextAlign.left,
              style: new TextStyle(
                color: UGrowColors.getColor("#333333"),
                fontSize: ScreenUtil.getInstance().setWidth(48),
              ),
            ),
          ),
          new Container(
            margin: new EdgeInsets.only(
              top: ScreenUtil.getInstance().setWidth(36),
              left: ScreenUtil.getInstance().setWidth(36),
              right: ScreenUtil.getInstance().setWidth(36),
            ),
            width: ScreenUtil.screenWidthDp -
                ScreenUtil.getInstance().setWidth(36 + 36),
            child: new Text(
              getPublishDate(data),
              maxLines: 1,
              softWrap: true,
              textAlign: TextAlign.left,
              style: new TextStyle(
                color: UGrowColors.getColor("#999999"),
                fontSize: ScreenUtil.getInstance().setWidth(38),
              ),
            ),
          ),
          new Container(
            margin: new EdgeInsets.only(
              bottom: 0,
              top: ScreenUtil.getInstance().setWidth(26),
            ),
            height: ScreenUtil.getInstance().setWidth(2),
            child: new Container(
              height: ScreenUtil.getInstance().setWidth(2),
              width: ScreenUtil.screenWidthDp -
                  ScreenUtil.getInstance().setWidth(36 + 36),
              color: UGrowColors.getColor("#cccccc"),
            ),
          ),
        ],
      ),
    );
  }

  //三张图Item
  Widget _createThreeImageItem(data) {
    List<String> imageList = ((data["customImage"]) as String).split(",");
    return new Container(
      child: new Column(
        children: <Widget>[
          new Container(
            margin: new EdgeInsets.only(
              left: ScreenUtil.getInstance().setWidth(36),
              right: ScreenUtil.getInstance().setWidth(36),
              top: ScreenUtil.getInstance().setWidth(28),
            ),
            width: ScreenUtil.screenWidthDp -
                ScreenUtil.getInstance().setWidth(36 + 36),
            child: new Text(
              data["title"],
              maxLines: 1,
              softWrap: true,
              overflow: TextOverflow.ellipsis,
              style: new TextStyle(
                  color: UGrowColors.getColor("#333333"),
                  fontSize: ScreenUtil.getInstance().setWidth(48)),
            ),
          ),
          new Container(
            height: ScreenUtil.getInstance().setWidth(240),
            margin: new EdgeInsets.only(
              top: ScreenUtil.getInstance().setWidth(18),
              left: ScreenUtil.getInstance().setWidth(35),
            ),
            child: new Row(
              children: <Widget>[
                new Container(
                  child: new CachedNetworkImage(
                    imageUrl: imageList[0],
                    placeholder: (context, url) {
                      return new Image.asset(
                        "images/image_loading1.png",
                        height: ScreenUtil.getInstance().setWidth(240),
                        width: ScreenUtil.getInstance().setWidth(320),
                        fit: BoxFit.fill,
                      );
                    },
                    errorWidget: (context, url, builder) {
                      return new Icon(Icons.error);
                    },
                    height: ScreenUtil.getInstance().setWidth(240),
                    width: ScreenUtil.getInstance().setWidth(320),
                    fit: BoxFit.fill,
                  ),
                ),
                new Container(
                  margin: new EdgeInsets.only(
                    left: ScreenUtil.getInstance().setWidth(26),
                  ),
                  child: new CachedNetworkImage(
                    imageUrl: imageList[1],
                    placeholder: (context, url) {
                      return new Image.asset(
                        "images/image_loading1.png",
                        height: ScreenUtil.getInstance().setWidth(240),
                        width: ScreenUtil.getInstance().setWidth(320),
                        fit: BoxFit.fill,
                      );
                    },
                    errorWidget: (context, url, builder) {
                      return new Icon(Icons.error);
                    },
                    height: ScreenUtil.getInstance().setWidth(240),
                    width: ScreenUtil.getInstance().setWidth(320),
                    fit: BoxFit.fill,
                  ),
                ),
                new Container(
                  margin: new EdgeInsets.only(
                    left: ScreenUtil.getInstance().setWidth(26),
                  ),
                  child: new CachedNetworkImage(
                    imageUrl: imageList[2],
                    placeholder: (context, url) {
                      return new Image.asset(
                        "images/image_loading1.png",
                        height: ScreenUtil.getInstance().setWidth(240),
                        width: ScreenUtil.getInstance().setWidth(320),
                        fit: BoxFit.fill,
                      );
                    },
                    errorWidget: (context, url, builder) {
                      return new Icon(Icons.error);
                    },
                    height: ScreenUtil.getInstance().setWidth(240),
                    width: ScreenUtil.getInstance().setWidth(320),
                    fit: BoxFit.fill,
                  ),
                ),
              ],
            ),
          ),
          new Container(
            margin: new EdgeInsets.only(
              top: ScreenUtil.getInstance().setWidth(36),
              left: ScreenUtil.getInstance().setWidth(36),
              right: ScreenUtil.getInstance().setWidth(36),
            ),
            width: ScreenUtil.screenWidthDp -
                ScreenUtil.getInstance().setWidth(36 + 36),
            child: new Text(
              getPublishDate(data),
              maxLines: 1,
              softWrap: true,
              textAlign: TextAlign.left,
              style: new TextStyle(
                color: UGrowColors.getColor("#999999"),
                fontSize: ScreenUtil.getInstance().setWidth(38),
              ),
            ),
          ),
          new Container(
            margin: new EdgeInsets.only(
              bottom: 0,
              top: ScreenUtil.getInstance().setWidth(26),
            ),
            height: ScreenUtil.getInstance().setWidth(2),
            child: new Container(
              height: ScreenUtil.getInstance().setWidth(2),
              width: ScreenUtil.screenWidthDp -
                  ScreenUtil.getInstance().setWidth(36 + 36),
              color: UGrowColors.getColor("#cccccc"),
            ),
          ),
        ],
      ),
    );
  }

  //从data中组合时间副标题的文字，乱的一逼
  String getPublishDate(data) {
    String publishDate = data["publishDate"];
    int year = DateTime.now().year;
    int month = DateTime.now().month;
    int day = DateTime.now().day;
    if (int.parse(publishDate.substring(0, 4)) == year &&
        int.parse(publishDate.substring(5, 7)) == month &&
        int.parse(publishDate.substring(8, 10)) == day) {
      publishDate = publishDate.substring(11, 19);
    } else if (int.parse(publishDate.substring(0, 4)) == year) {
      publishDate = publishDate.substring(5, 10);
    } else {
      publishDate = publishDate.substring(0, 10);
    }

    if (!TextUtil.isEmpty(data["referName"])) {
      publishDate = data["referName"] + " " + publishDate;
    }
    return publishDate;
  }
}
